var instanceDBMenu = [];
Ext.onReady(function() {
    Ext.each(instanceDBS , function(db) {
        instanceDBMenu.push({
            text:db.data,handler:function() {
                addNewFastDBJob(db.data);
            }
        });
    });
    Ext.create('Ext.Viewport', {
        layout:'fit',
        items:[createExportViewList()]
    }); 
    exportByParams(requestParams);
});

var saveExportParamsToLocal = function(params , key) {
    var rememberParams = getExportParamsByLocal();
    Ext.apply(rememberParams , params);
    SimpleStorageUtils.set(key , JSON.stringify(rememberParams));
};

var getExportParamsByLocal = function(key) {
    var rememberParams = SimpleStorageUtils.get(key);
    if(rememberParams) {
        rememberParams = JSON.parse(rememberParams);
    }else {
        rememberParams = {};
    }
    return rememberParams;
};
var getExportDBParams = function(dbName) {
    var dbDefaults = {
        dbName:dbName,
        tableRowsLimit:'0',
        fileType:'SQL_Insert',
        fileCharset:'utf8',
        exportMethod:'all',
        compressSqlScript:true,
        compressInsert:true,
        enableCsvTitleRow:true,
        everyTableFile:false,
        "createDesc":"",
        "exportProcedure":true,
        "exportFunction":true,
        "exportTrigger":true,
        "exportView":true,
        "exportEvent":false,
        "exportBlob":false,
        "exportBinary":true,
        "exportClob":true,
        "exportRef":true,
        "exportIndex":true,
        "exportDropTable":true,
        "exportTruncateTable":true
    };
    var initData = getExportParamsByLocal("dms_mysql_export_db_params");
    Ext.apply(dbDefaults , initData);
    return dbDefaults;
};

var getExportTableParams = function() {
    var tableDefaults = {
        fileType:"SQL_Insert",
        fileCharset:"utf8",
        exportMethod:"all",
        compressSqlScript:true,
        compressInsert:true,
        enableCsvTitleRow:true,
        tableRowsLimit:'0',
        "exportBlob":false,
        "exportBinary":true,
        "exportClob":true,
        "exportRef":true,
        "exportIndex":true,
        "exportDropTable":true,
        "exportTruncateTable":true
    };
    var initData = getExportParamsByLocal("dms_mysql_export_tab_params");
    Ext.apply(tableDefaults , initData);
    return tableDefaults;
};
var getExportSQLParams = function(dbName) {
    var defaults = {
        fileType:"CSV",
        fileCharset:"utf8",
        compressInsert:true,
        enableCsvTitleRow:true,
        tableRowsLimit:'200000',
        "exportBlob":false,
        "exportBinary":true,
        "exportClob":true
    };
    var initData = getExportParamsByLocal("dms_mysql_export_sql_params");
    Ext.apply(defaults , initData);
    if(defaults['dbName'] !== dbName) {
        defaults['sql'] = undefined;
        defaults['createDesc'] = undefined;
    }
    return defaults;
};

var exportByParams = function(requestParams) {
    if(requestParams) {
        var paramObject = jsonDecode(requestParams);
        if(paramObject['exportType'] == 'table' && paramObject['tableName']) {
            addTableJob(paramObject);
        }else if(paramObject['exportType'] == 'db') {
            addNewDBJob(paramObject);
        }
    }
};

var fileTypeArray = [
   // {data:'CSV' , label:'CSV'},
    {data:'SQL_Insert' , label:'SQL'}
];
var fileTypeArray2 = [
    {data:'EXCEL' , label:'EXCEL'},
    {data:'SQL_Insert' , label:'SQL_Insert'}
];
var fileCharsetTypeArray = [
    {data:'utf8'},
    {data:'gbk'}
];
var okOrNoDataArray = [
    {data:'1' , label:'Y'},
    {data:'0' , label:'N'}
];
var rowsLimitArray = [
    {data:'50' , label:'50条(单表)'},
    {data:'100' , label:'100条(单表)'},
    {data:'200' , label:'200条(单表)'}
];
var tableRowsLimitArray = [];
for(var i = 0 , size = rowsLimitArray.length ; i < size ; i++) {
    tableRowsLimitArray.push(rowsLimitArray[i]);
}
tableRowsLimitArray.push({data:'0' , label:'无限制'});
var isOK = function(v) {
    return v ? 'Y' : 'N';
};
var allStatusRenderer = function(v,c,row) {
    return statusRenderer(v , row.data['statusName'] , row);
};
var statusRenderer = function(v , display , row) {
    var end = '';
    if(row.data['allFileName']) {
        end = ' <a style="color: red" href="javascript:downloadAllFile(\'' + getJSONValue(row.data , 'id') + '\')" >下载</a>';
    }
    var showMonitorHref = ' <a style="color: red" href="javascript:showMonitor(\'' + getJSONValue(row.data , 'id') + '\')" >详情</a>';
    if(v == 'NEW') {
        return '<img src="../img/icon/start.png" height="14"/>' + display + showMonitorHref;
    }else if(v == 'EXPORT' || v == 'UPLOAD') {
        return '<img src="../img/icon/run.png" height="14"/>' + display + showMonitorHref;
    }else if(v == 'END') {
        return '<img src="../img/websql/icons/accept.png" height="14"/> ' + display + end;
    }else if(v == 'ERROR') {
        return '<img src="../img/icon/error.png" height="14"> ' + display + showMonitorHref;
    }
};
var exportMethodConvert = function(v) {
    if(v == 'data') {
        return '数据';
    }else if(v == 'create_script') {
        return '结构';
    }else {
        return '数据和结构';
    }
};
var createOnlyDataAdvanceWindow = function(initParam) {
    var form = new IDB.FormPanel({
        defaults:{
            bodyPadding:5,
            padding:'0 5 0 5',
            xtype:'fieldset',
            width:520,
            defaults:{
                autoFitErrors:false,//自动调整错误提示时候的宽度
                labelSeparator:' : ',
                labelWidth:80,
                width:500,
                labelAlign:'right',
                xtype:'textfield'
            }
        },
        items:[
            {
                title:'数据选项',
                defaults:{
                    hiddenLabel:true,inputValue:'Y',xtype:'checkboxfield'
                },
                items:[
                    {name:'exportBlob',checked:initParam['exportBlob'],boxLabel:'导出TINYBLOB、BLOB、MEDIUMBLOB、LONGBLOB类型（输出格式为16进制）'},
                    {name:'exportBinary',checked:initParam['exportBinary'],boxLabel:'导出BINARY、VARBINARY类型（输出格式为16进制）'},
                    {name:'exportClob',checked:initParam['exportClob'],boxLabel:'导出TINYTEXT、TEXT、MEDIUMTEXT、LONGTEXT类型'}
                ]
            }
        ]
    });
    var win = new Ext.window.Window({
        height:220 , width:600 , title:'高级选项',
        modal:true,layout:'fit',closable:false,buttonAlign:'center',items:[form],
        buttons:[{
            text:'确定',handler:function() {
                win.hide();
            }
        }],
        getAdvanceValues:function() {
            return form.getValues();
        },
        getAdvanceFormValues:function() {
            return form.getForm().getFieldValues();
        }
    });
    return win;
};
var createAdvanceWindow = function(initParams) {
    var form = new IDB.FormPanel({
        defaults:{
            bodyPadding:5,
            padding:'0 5 0 5',
            xtype:'fieldset',
            width:520,
            columnWidth:.98,
            defaults:{
                autoFitErrors:false,//自动调整错误提示时候的宽度
                labelSeparator:' : ',
                labelWidth:80,
                width:500,
                labelAlign:'right',
                xtype:'textfield'
            }
        },
        layout:'column',
        items:[
            {
                title:'数据选项',
                defaults:{
                    xtype:'checkboxfield',
                    hiddenLabel:true,
                    inputValue:'Y'
                },
                items:[
                    {name:'exportBlob',checked:initParams['exportBlob'],boxLabel:'导出TINYBLOB、BLOB、MEDIUMBLOB、LONGBLOB类型（输出格式为16进制）'},
                    {name:'exportBinary',checked:initParams['exportBinary'],boxLabel:'导出BINARY、VARBINARY类型（输出格式为16进制）'},
                    {name:'exportClob',checked:initParams['exportClob'],boxLabel:'导出TINYTEXT、TEXT、MEDIUMTEXT、LONGTEXT类型'}
                ]
            },
            {
                xtype:'panel',
                columnWidth:.98,
                bodyPadding:0,
                border:false,
                id:'only_sql_insert_options',
                defaults:{
                    bodyPadding:5,
                    padding:'0 5 0 5',
                    xtype:'fieldset',
                    width:500,
                    defaults:{
                        autoFitErrors:false,//自动调整错误提示时候的宽度
                        labelSeparator:' : ',
                        labelWidth:80,
                        width:500,
                        labelAlign:'right',
                        xtype:'textfield'
                    }
                },
                items:[{
                    title:'表结构选项',
                    defaults:{
                        xtype:'checkboxfield',inputValue:'Y',hiddenLabel:true
                    },
                    items:[
                        {name:'exportRef',checked:initParams['exportRef'],boxLabel:'包含外键'},
                        {name:'exportIndex',checked:initParams['exportIndex'],boxLabel:'包含索引'}
                    ]
                },{
                    title:'SQL脚本扩展选项',
                    defaults:{
                        xtype:'checkboxfield',inputValue:'Y',hiddenLabel:true
                    },
                    items:[
                        {name:'exportDropTable',checked:initParams['exportDropTable'],boxLabel:'在create语句前生成drop table语句'},
                        {name:'exportTruncateTable',checked:initParams['exportTruncateTable'],boxLabel:'在insert语句前生成truncate table语句'}
                    ]
                }]

            }
        ]
    });
    var win = new Ext.window.Window({
        height:380 , width:600 , title:'高级选项',
        modal:true,layout:'fit',closable:false,buttonAlign:'center',items:[form],
        buttons:[{
            text:'确定',handler:function() {
                win.hide();
            }
        }],
        getAdvanceValues:function() {
            return form.getValues();
        },
        getAdvanceFormValues:function() {
            return form.getForm().getFieldValues();
        },
        showCSV:function() {
            Ext.getCmp('only_sql_insert_options').hide();
            win.setHeight(200);
            win.show();
        },
        showSQL:function() {
            Ext.getCmp('only_sql_insert_options').show();
            win.setHeight(380);
            win.show();
        }
    });
    return win;
};
var nowWindow;
var closeNowWindow = function() {
    if(nowWindow) {
        nowWindow.close();
        nowWindow = null;
    }
    closeNowMonitorWindow();
};
var tmpNum = 0;
var addTableJob = function(data) {
    closeNowWindow();
    var initParams = getExportTableParams();
    var projectStore = new Ext.data.Store({
		fields:['data','label'],
		data : projectListArray
	});
    var form = new IDB.FormPanel({
        region:'center',
        layout:'column',
        defaults:{margin: '2 2 2 0',width:660,columnWidth:1,labelWidth:90},
        items:[
            {
                columnWidth:.5,
                width:230,
                fieldLabel:'文件类型',
                editable:false,
                blankText:'文件类型不能为空',
                xtype:'combo',
                name:'fileType',
                triggerAction:'all',
                displayField:'label',
                valueField:'data',
                queryMode:'local',
                forceSelection:true,
                typeAhead:true,
                value:initParams['fileType'],
                store:new Ext.data.Store({
                    fields:['data' , 'label'],
                    data:fileTypeArray
                })
            },{
                columnWidth:.5,
                fieldLabel:'文件字符集',
                editable:false,
                blankText:'字符集选项不能为空',
                xtype:'combo',
                name:'fileCharset',
                triggerAction:'all',
                displayField:'data',
                valueField:'data',
                queryMode:'local',
                value:initParams['fileCharset'],
                forceSelection:true,
                typeAhead:true,
                store:new Ext.data.Store({
                    fields:['data'],
                    data:fileCharsetTypeArray
                })
            },
            {
                xtype:'radiogroup',
                fieldLabel:'导出内容',
                id:'exportMethodField',
                columns:3,
                items:[
                    {name:'exportMethod',inputValue:'all',boxLabel:'结构和数据',checked:(initParams['exportMethod'] === "all")},
                    {name:'exportMethod',inputValue:'data',boxLabel:'数据',checked:(initParams['exportMethod'] === "data")},
                    {name:'exportMethod',inputValue:'create_script',boxLabel:'结构',checked:(initParams['exportMethod'] === "create_script")}
                ]
            },
            {
                xtype:'checkboxgroup',
                fieldLabel:'选项',
                id:'check_option',
                columns:1,
                items:[
                    {
                        name:'compressInsert',
                        inputValue:'Y',
                        checked:initParams['compressInsert'],
                        boxLabel:'insert语句合并'//（以5M为单位将多个insert语句进行合并）
                    },
                    {
                        name:'enableCsvTitleRow',
                        inputValue:'Y',
                        hidden:true,
                        checked:initParams['enableCsvTitleRow'],
                        boxLabel:'选中此项CSV第1行为属性名，否则第1行为数据'
                    }
                ]
            },
            {
                fieldLabel:'数据库',
                name:'dbName',
                readOnly:true,
                blankText:'数据库选项不能为空',
                value:data['dbName']
            },
            {
                fieldLabel:'表名',
                name:'tables',
                readOnly:true,
                value:data['tableName']
            },{
                fieldLabel:'行数限制',
                editable:false,
                xtype:'combo',
                name:'tableRowsLimit',
                triggerAction:'all',
                displayField:'label',
                valueField:'data',
                queryMode:'local',
                value:initParams['tableRowsLimit'],
                forceSelection:true,
                typeAhead:true,
                store:new Ext.data.Store({
                    fields:['data' , 'label'],
                    data:tableRowsLimitArray
                })
            },
            {
                fieldLabel:'WHERE条件',
                xtype:'textarea',
                height:65,
                maxLength:4000,
                emptyText:'请在这里输入where条件,末尾一定不要加英文分号！！！',
                maxLengthText:'请不要超过4000个字符',
                name:'whereCondition',
                allowBlank:true
            },
            {
            	fieldLabel:'项目组',
            	xtype:'combo',
            	triggerAction:'all',
            	displayField:'label',
            	valueField:'data',
            	queryMode:'local',
            	name:'projectName',
            	forceSelection:true,
            	typeAhead:true,
            	editable:false,
            	store:projectStore
            },
            {
                fieldLabel:'描述',
                xtype:'textarea',
                height:65,
                maxLength:1024,
                maxLengthText:'请不要超过1024个字符',
                name:'createDesc',
                allowBlank:true
            }
        ]
    });

    var fileTypeField = form.getForm().findField('fileType');
    var setExportCreateScript = function() {
        if(fileTypeField.getValue() == 'SQL_Insert') {
            Ext.getCmp('exportMethodField').show();
            form.getForm().findField('compressInsert').show();
            form.getForm().findField('enableCsvTitleRow').hide();
        }else {
            Ext.getCmp('exportMethodField').hide();
            form.getForm().findField('compressInsert').hide();
            form.getForm().findField('enableCsvTitleRow').show();
        }
    };
    fileTypeField.on('select' , setExportCreateScript);
    setExportCreateScript();
    var submitTO = function() {
        if(form.isValid()) {
            var params = form.getValues();
            Ext.apply(params , advanceWindow.getAdvanceValues());

            var formParams = form.getForm().getFieldValues();
            Ext.apply(formParams , advanceWindow.getAdvanceFormValues());

            saveExportParamsToLocal(formParams , "dms_mysql_export_tab_params");

            params['exportMode'] = "db";
            var tableCondition = {};
            if(params['whereCondition']) {
                tableCondition['table_' + params['tables']] = params['whereCondition'];
            }
            params['whereCondition'] = jsonToString(tableCondition);
            
            params['isLocal'] = isLocal;
            params['dataBaseType'] = now_db_type;
            params['dataBaseId'] = dataBase_id;
            params['dataSourceId'] = dataSource_id;
            params['dataSource'] = data_source;
            win.getEl().mask('正在提交任务，请等待....');
            ajax({
                url:getRoot()+'/dataManage/saveExportDataJob',
                params:params,
                success:function(resp) {
                    win.getEl().unmask();
                    var json = jsonDecode(resp.responseText);
                    if(json.success) {
                        public_export_grid.store.load();
                        showMonitor(json.root);
                        win.close();
                    }else {
                        $.message.error(json.root);
                    }
                },
                failure:function() {
                    win.getEl().unmask();
                }
            })
        }
    };
    var win = new IDB.Window({
        title:'新增导出任务',
        width:600,
        height:400,
        closable:true,
        layout:'border',
        items:[form],
        buttons:[{
            text:'更多选项',handler:function() {
                if(fileTypeField.getValue() == 'SQL_Insert') {
                    advanceWindow.showSQL();
                }else {
                    advanceWindow.showCSV();
                }
            }
        },{
            text:'确定',handler:submitTO
        },{
            text:'关闭',handler:function() {
                win.close();
            }
        }]
    });
    var advanceWindow = createAdvanceWindow(initParams);
    win.on('beforedestroy' , function() {
        advanceWindow.close();
    });
    nowWindow = win;
};
var getMonitorBaseInfoByRow = function(row , date) {
    if(row['exportMode'] == 'sql') {
        return '======================================================================\n' +
            '     当前状态：' + Ext.util.Format.htmlDecode(row['statusName']) +  "\n" +
            '     刷新时间：' + Ext.util.Format.date(date , 'Y-m-d H:i:s') + '\n' +
            '     ' + Ext.util.Format.htmlDecode(row['nowLog'] || '等待执行....') +  "\n" +
            '     SQL语句：\n' +
            '     ' + String(row['sql']).replaceAll("\n" , "\n     ") + '\n' +
            '======================================================================\n';
    }
    return '======================================================================\n' +
        '     当前状态：' + Ext.util.Format.htmlDecode(row['statusName']) +  "\n" +
        '     已导出表：' + Ext.util.Format.htmlDecode(row['exportedTabs'])  + " / " + Ext.util.Format.htmlDecode(row['exportTabNum']) +  "\n" +
        '     刷新时间：' + Ext.util.Format.date(date , 'Y-m-d H:i:s') + '\n' +
        '     ' + Ext.util.Format.htmlDecode(row['nowLog'] || '等待执行....') +  "\n" +
        '======================================================================\n';
};
var now_monitor_window;
var closeNowMonitorWindow = function() {
    if(now_monitor_window) {
        now_monitor_window.close();
        now_monitor_window = null;
    }
};
var isMonitorTask = false;
var showBackGround = function() {
    document.getElementById('display_background').style.display = "block";
    var screenWidth = document.body.clientWidth;
    var screenHeight = document.body.clientHeight;

    var width = screenWidth - 160;
    var height = screenHeight - 70;

    var canvas = document.getElementById('my_canvas');
    canvas.style.height = height + "px";
    canvas.style.width = width + "px";
};
var showMonitorDoing = function(json , id) {
    if(json['exportStatus'] == 'END' && json['exportMode'] != 'sql') {
        return showDetail(id);
    }
    var use = getProcess(json);
    var sql = json['sql'];
    var processBar = new Ext.ProgressBar({
        text:'当前进度：' + use + "%",paddingTop:10,region:'north',margin:'3 12 3 12'
    });
    processBar.updateProgress(parseFloat(use)/100 , '当前进度：' + use + "%&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;已导出总行数：" + json['nowRows'] , true);
    var win = now_monitor_window = new IDB.Window({
        title:'任务进度跟踪(每2s刷新一次进度)',
        layout:'border',
        width:680,
        height:450,
        items:[{
            region:'north',height:30,border:false,layout:'fit',items:[processBar],id:'processBarArea'
        },{
            html:'详情',region:'center',layout:'fit',border:false,baseCls:'log_content',id:'oneTableLog',xtype:'container'
        }],
        buttons:[{
            text:'关闭',handler:function() {
                win.close();
            }
        },{
            hidden:true,
            id:'monitor_download_file',
            text:'下载文件',handler:function() {
                downloadAllFile(id);
            }
        }],
        listeners:{
            'afterrender' : function() {
                setTimeout(function() {
                    var elements = Ext.select(".x-mask");
                    elements.each(function(el) {
                        //console.log(el.getStyle('z-index'));
                        el.setStyle("z-index", '999');
                        //console.log(el.getStyle('z-index'));
                    }, this) ;
                } , 200);

            }
        }
    });
    var nowLogContentDom = Ext.getCmp('oneTableLog').el.dom;
    nowLogContentDom.innerHTML = "<pre>" + getMonitorBaseInfoByRow(json , new Date()) + (json['log'] || '') + "</pre>";
    if(json['exportStatus'] == 'END') {
        win.setTitle("任务已执行完成");
    }else {

        showBackGround();
        isMonitorTask = true;
        var task = {
            interval:2000,
            run:function() {
                var date = new Date();
                ajax({
                    url:'/data/export/monitorExportJob.do?id='+id,
                    success:function(resp) {
                        var json = jsonDecode(resp.responseText);
                        if(json.success) {
                            json = json.root;
                            json['sql'] = sql;
                            var use = getProcess(json);
                            processBar.updateProgress(parseFloat(use)/100 , '当前进度：' + use + "%&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;已导出总行数：" + json['nowRows'] , true);
                            nowLogContentDom.innerHTML = "<pre>" + getMonitorBaseInfoByRow(json , new Date()) + (json['log'] || '') + "</pre>";
                            nowLogContentDom.scrollTop = nowLogContentDom.scrollHeight;
                            if(json['exportStatus'] == 'END') {
                                Ext.TaskManager.stop(task);
                                isMonitorTask = false;
                                document.getElementById('display_background').style.display = "none";
                                win.setTitle("详情");
                                Ext.getCmp('monitor_download_file').show();
                                downloadAllFile(id);
                            }else if(json['exportStatus'] == 'ERROR') {
                                Ext.TaskManager.stop(task);
                                document.getElementById('display_background').style.display = "none";
                                isMonitorTask = false;
                                win.setTitle("查看错误信息");
                                Ext.getCmp('processBarArea').hide();
                            }
                        }else {
                            $.message.error(json.root);
                        }
                    }
                });
            }
        };
        if(json['exportStatus'] != 'ERROR') {
            Ext.TaskManager.start(task);
            win.on('beforedestroy' , function() {
                Ext.TaskManager.stop(task);
                document.getElementById('display_background').style.display = "none";
                isMonitorTask = false;
                public_export_grid.store.load();
                now_monitor_window = null;
            });
        }else {
            win.setTitle("查看错误信息");
            Ext.getCmp('processBarArea').hide();
        }
    }
};
var showMonitor = function(id) {
    Ext.getBody().mask('正在加载....');
    ajax({
        url:'/data/export/monitorExportJob.do?id='+id + "&firstTime=Y",
        success:function(resp) {
            Ext.getBody().unmask();
            var json = jsonDecode(resp.responseText);
            if(json.success) {
                showMonitorDoing(json.root , id);
            }else {
                $.message.error('提示' , json.root);
            }
        },
        failure:function() {
            Ext.getBody().unmask();
        }
    });
};
var editWhereCondition = function() {
    nowWindow.editWhereCondition();
};
var getParentDBName = function() {
    if(window.parent) {
        return window.parent.object_panel.getNowDBName();
    }
};
var addNewFastDBJob = function(dbName) {
    Ext.getBody().mask('正在提交导出任务....');
    ajax({
        url:'/data/export/exportDbAll.do',
        params:{dbName:dbName},
        success:function(resp) {
            Ext.getBody().unmask();
            var json = jsonDecode(resp.responseText);
            if(json.success) {
                public_export_grid.store.load();
                showMonitor(json.root);
            }else {
                $.message.error(json.root);
            }
        },
        failure:function() {
            Ext.getBody().unmask();
        }
    });
};
var addNewDBJob = function(data) {
    var dbName = '';
    if(data) {
        dbName = data['dbName'];
    }else {
        dbName = getParentDBName();
    }
    closeNowWindow();
    var initParams = getExportDBParams(dbName);
    var form = new IDB.FormPanel({
        region:'center',
        bodyStyle: 'border-style:solid;border-width:1px;border-color:#eee;',border:true,
        defaults:{
            padding:'0 3 3 3',
            xtype:'fieldset',
            layout:'column',
            width:540,
            defaults:{
                margin: '1 1 1 0',
                labelAlign:'right',
                width:500,
                columnWidth:1,
                labelWidth:75
            }
        },
        items:[
            {
                title:'导出基本信息',
                items:[{
                    columnWidth:.5,
                    fieldLabel:'数据库',
                    xtype:'combo',
                    name:'dbName',
                    blankText:'数据库选项不能为空',
                    triggerAction:'all',
                    displayField:'label',
                    valueField:'data',
                    queryMode:'local',
                    forceSelection:true,
                    typeAhead:true,
                    value:initParams['dbName'],
                    store:new Ext.data.Store({
                        fields:['data','label'],
                        data:instanceDBS
                    })
                },{
                    columnWidth:.5,
                    fieldLabel:'行数限制',
                    editable:false,
                    xtype:'combo',
                    name:'tableRowsLimit',
                    triggerAction:'all',
                    displayField:'label',
                    valueField:'data',
                    queryMode:'local',
                    value:initParams['tableRowsLimit'],
                    forceSelection:true,
                    typeAhead:true,
                    store:new Ext.data.Store({
                        fields:['data' , 'label'],
                        data:tableRowsLimitArray
                    })
                },{
                    columnWidth:.5,
                    width:230,
                    fieldLabel:'文件类型',
                    editable:false,
                    blankText:'文件类型不能为空',
                    xtype:'combo',
                    name:'fileType',
                    triggerAction:'all',
                    displayField:'label',
                    valueField:'data',
                    queryMode:'local',
                    forceSelection:true,
                    typeAhead:true,
                    value:initParams['fileType'],
                    store:new Ext.data.Store({
                        fields:['data' , 'label'],
                        data:fileTypeArray
                    })
                },{
                    columnWidth:.5,
                    fieldLabel:'文件字符集',
                    editable:false,
                    blankText:'字符集选项不能为空',
                    xtype:'combo',
                    name:'fileCharset',
                    triggerAction:'all',
                    displayField:'data',
                    valueField:'data',
                    queryMode:'local',
                    value:initParams['fileCharset'],
                    forceSelection:true,
                    typeAhead:true,
                    store:new Ext.data.Store({
                        fields:['data'],
                        data:fileCharsetTypeArray
                    })
                },
                    {
                        xtype:'radiogroup',
                        fieldLabel:'导出内容',
                        id:'exportMethodField',
                        columns:3,
                        items:[
                            {name:'exportMethod',inputValue:'all',boxLabel:'结构和数据',checked:(initParams['exportMethod'] === 'all')},
                            {name:'exportMethod',inputValue:'data',boxLabel:'数据',checked:(initParams['exportMethod'] === 'data')},
                            {name:'exportMethod',inputValue:'create_script',boxLabel:'结构',checked:(initParams['exportMethod'] === 'create_script')}
                        ]
                    },
                    {
                        xtype:'checkboxgroup',
                        fieldLabel:'文件选项',
                        id:'check_option',
                        columns:1,
                        items:[
                            {
                                name:'compressSqlScript',
                                hidden:true,
                                inputValue:'Y',
                                checked:initParams['compressSqlScript'],
                                boxLabel:'SQL文件合并（多个表的SQL语句将合并到同一个总文件中）'
                            },
                            {
                                name:'compressInsert',
                                inputValue:'Y',
                                checked:initParams['compressInsert'],
                                boxLabel:'insert语句合并'//（以5M为单位将多个insert语句进行合并）
                            },
                            {
                                name:'enableCsvTitleRow',
                                inputValue:'Y',
                                hidden:true,
                                checked:initParams['enableCsvTitleRow'],
                                boxLabel:'包含属性行（选中此项CSV第1行为属性名，否则第1行为数据）'
                            },
                            {
                                name:'everyTableFile',
                                inputValue:'Y',
                                checked:initParams['everyTableFile'],
                                boxLabel:'生成单表文件（详情中可下载单表文件，但会影响速度）'
                            }
                        ]
                    },
                    {
                        fieldLabel:'描述',
                        xtype:'textarea',
                        height:90,
                        maxLength:1024,
                        maxLengthText:'请不要超过1024个字符',
                        name:'createDesc',
                        allowBlank:true
                    },{
                        hidden:true,
                        id:'csv_more_options',
                        xtype:'panel',
                        html:'<span style="margin-right: 13px;padding-top: 10px;float: right">' +
                        '<input type="button" value="更多选项" onclick="nowWindow.showAdvanceWindow(\'CSV\');" class="button_class_1" style="width: 100px;height: 34px;"/>' +
                        '</span>'
                    }]
            },{
                title:'导出附加内容',
                id:'export_additional_content',
                items:[{
                    xtype:'checkboxgroup',
                    columns:3,
                    items:[
                        {xtype:'checkboxfield',name:'exportProcedure',inputValue:'Y',hiddenLabel:true,checked:initParams['exportProcedure'],boxLabel:'存储过程'},
                        {xtype:'checkboxfield',name:'exportFunction',inputValue:'Y',hiddenLabel:true,checked:initParams['exportFunction'],boxLabel:'函数'},
                        {xtype:'checkboxfield',name:'exportTrigger',inputValue:'Y',hiddenLabel:true,checked:initParams['exportTrigger'],boxLabel:'触发器'},
                        {xtype:'checkboxfield',name:'exportView',inputValue:'Y',hiddenLabel:true,checked:initParams['exportView'],boxLabel:'视图'},
                        {xtype:'checkboxfield',name:'exportEvent',inputValue:'Y',hiddenLabel:true,checked:initParams['exportEvent'],boxLabel:'事件'},
                        {
                            xtype:'panel',
                            html:'<span style="margin-right: 13px;padding-top: 10px;float: right">' +
                            '<input type="button" value="更多选项" onclick="nowWindow.showAdvanceWindow(\'SQL\');" class="button_class_1" style="width: 100px;height: 34px;"/>' +
                            '</span>'
                        }
                    ]
                }]
            }

        ]
    });
    var iframeWidth = document.body.clientWidth;
    var preWidth = 960 , preGridPanel = 400 , preInitWidth = preWidth - preGridPanel;
    if(iframeWidth < 1000) {
        preWidth = iframeWidth - 10;
        preGridPanel = 260;
        preInitWidth = preWidth - preGridPanel;
    }
    this.editWhereCondition = function() {
        var tableName = gridTempRow.get("id");
        var whereCondition = gridTempRow.get("whereCondition");
        var area = new Ext.form.field.TextArea({emptyText:'请在这里输入where条件',value:whereCondition,maxLength:4000});
        var win = new IDB.Window({
            width:600,height:300,title:'为导出表[' + tableName + "]设置where条件",layout:'fit',
            items:[area],
            buttons:[{
                text:'确定',handler:function() {
                    var value = area.getValue();
                    if(value.length > 4000) {
                        return $.message.warning('WHERE条件请不要超过4000个字符，较长的条件请使用【SQL结果集导出】功能。');
                    }
                    gridTempRow.set('whereCondition' , area.getValue());
                    win.close();
                }
            },{
                text:'取消',handler:function() {
                    win.close();
                }
            }]
        });
    };
    var gridTempRow = null;
    var whereConditionWidth = (iframeWidth < 1000 ? 100 : 200);
    var grid = new Ext.grid.Panel({
        hidden:true,
        selModel:new Ext.selection.CheckboxModel({checkOnly:true}),
        multiSelect:true,
        region:'east',
        height:200,
        width:preGridPanel,
        viewConfig: {
            enableTextSelection: true
        },
        columns:[
            {text: '表名',  dataIndex: 'id', flex:1 ,sortable:false},
            {text:'WHERE条件' , dataIndex:'whereCondition',width:whereConditionWidth,renderer:function(v,c,row) {
                if(v) {
                    return '<pre style="padding: 0;margin:0;font-family:新宋体,Lucida Console,monospace">' + v + '</pre>'
                        + ' <a href="javascript:editWhereCondition()">编辑</a>';
                }
                return '<a href="javascript:editWhereCondition()">编辑</a>';
            }}
        ],
        listeners:{
            cellclick:function(thiz , td , cellIndex , record) {
                gridTempRow = record;
            }
        },
        store:new Ext.data.Store({
            autoLoad:false,
            fields:['id','whereCondition'],
            proxy: {
                url:'/system/showOnlyTables.do',
                type: 'ajax',
                reader: {
                    root: 'root',
                    idProperty:'id'
                }
            }
        })
    });
    var databaseField = form.getForm().findField('dbName');
    var selectDBCallBack = function() {
        var height = document.body.clientHeight;
        var width = document.body.clientWidth;
        win.setWidth(preWidth);
        win.showAt((width - preWidth) / 2 , (height - 460) / 2);
        grid.show();
        grid.store.load({params:{dbName:databaseField.getValue(),panelKey:getPaneKey()}});
    };
    databaseField.on('select' , selectDBCallBack);
    var fileTypeField = form.getForm().findField('fileType');
    var setExportCreateScript = function() {
        if(fileTypeField.getValue() == 'SQL_Insert') {
            Ext.getCmp('exportMethodField').show();
            Ext.getCmp('export_additional_content').show();
            Ext.getCmp('csv_more_options').hide();
            form.getForm().findField('compressInsert').show();
            form.getForm().findField('enableCsvTitleRow').hide();
        }else {
            Ext.getCmp('exportMethodField').hide();
            Ext.getCmp('export_additional_content').hide();
            form.getForm().findField('compressInsert').hide();
            form.getForm().findField('enableCsvTitleRow').show();
            Ext.getCmp('csv_more_options').show();
        }
    };
    fileTypeField.on('select' , setExportCreateScript);
    setExportCreateScript();
    var submitTO = function() {
        if(form.isValid()) {
            var checkedTables = [];
            var whereConditionMap = {};
            var selectedRows = grid.getSelectionModel().getSelection();
            Ext.each(selectedRows , function(record) {
                checkedTables.push(record.get('id'));
                if(record.get('whereCondition')) {
                    whereConditionMap['table_' + record.get('id')] = record.get('whereCondition');
                }
            });
            if(checkedTables.length == 0) {
                return $.message.warning('没有选择任何表。');
            }
            var params = form.getValues();
            Ext.apply(params , advanceWindow.getAdvanceValues());

            var formParams = form.getForm().getFieldValues();
            Ext.apply(formParams , advanceWindow.getAdvanceFormValues());

            saveExportParamsToLocal(formParams , "dms_mysql_export_db_params");

            params.tables = checkedTables;
            params['exportMode'] = "db";
            params['whereCondition'] = jsonToString(whereConditionMap);
            
            params['isLocal'] = isLocal;
            params['dataBaseType'] = now_db_type;
            params['dataBaseId'] = dataBase_id;
            params['dataSourceId'] = dataSource_id;
            params['dataSource'] = data_source;
            win.getEl().mask('正在提交任务，请等待....');
            ajax({
                url:getRoot()+'/dataManage/saveExportDataJob',
                params:params,
                success:function(resp) {
                    win.getEl().unmask();
                    var json = jsonDecode(resp.responseText);
                    if(json.success) {
                        public_export_grid.store.load();
                        showMonitor(json.root);
                        win.close();
                    }else {
                        $.message.error(json.root);
                    }
                },
                failure:function() {
                    win.getEl().unmask();
                }
            })
        }
    };
    var win = new IDB.Window({
        title:'新增导出任务',
        width:preInitWidth,
        height:460,
        closable:true,
        layout:'border',
        items:[form , grid],
        buttons:[/*{
         text:'高级选项',handler:function() {
         advanceWindow.show();
         }
         },*/{
            text:'确定',handler:submitTO
        },{
            text:'关闭',handler:function() {
                win.close();
            }
        }],
        showAdvanceWindow:function(v) {
            if(v == 'CSV') {
                advanceWindow.showCSV();
            }else {
                advanceWindow.showSQL();
            }
        }
    });
    nowWindow = win;
    if(databaseField.getValue()) {
        selectDBCallBack();
    }
    var advanceWindow = createAdvanceWindow(initParams);
    win.on('beforedestroy' , function() {
        advanceWindow.close();
    });
};
var getProcess = function(data) {
    var use = 0;
    if(data['exportStatus'] == 'END') {
        return 100;
    }
    if(data['preRows'] && data['exportStatus'] != 'END') {
        use = ((parseFloat(data['nowRows']) / parseInt(data['preRows'])) * 100).toFixed(0);
        if(use >= 100) {
            use = 99;
        }
    }else {
        use = ((parseFloat(data['completeSize']) / parseInt(data['exportTabSize'])) * 100).toFixed(0);
    }
    return use;
};
var addNewSQLJob = function(data) {
    var dbName = '';
    if(data) {
        dbName = data['dbName'];
    }else {
        dbName = getParentDBName();
    }
    closeNowWindow();
    var initParam = getExportSQLParams(dbName);
    
    var projectStore = new Ext.data.Store({
		fields:['data','label'],
		data : projectListArray
	});
    
    var form = new IDB.FormPanel({
        region:'center',
        layout:'column',
        defaults:{margin: '2 2 2 0',width:500,columnWidth:1,labelWidth:100},
        items:[
            {
                columnWidth:.5,
                width:230,
                fieldLabel:'文件类型',
                editable:false,
                blankText:'文件类型不能为空',
                xtype:'combo',
                name:'fileType',
                triggerAction:'all',
                displayField:'label',
                valueField:'data',
                queryMode:'local',
                forceSelection:true,
                typeAhead:true,
                value:initParam['fileType'],
                store:new Ext.data.Store({
                    fields:['data' , 'label'],
                    data:fileTypeArray2
                })
            },{
                columnWidth:.5,
                fieldLabel:'文件字符集',
                editable:false,
                blankText:'字符集选项不能为空',
                xtype:'combo',
                name:'fileCharset',
                triggerAction:'all',
                displayField:'data',
                valueField:'data',
                queryMode:'local',
                value:initParam['fileCharset'],
                forceSelection:true,
                typeAhead:true,
                store:new Ext.data.Store({
                    fields:['data'],
                    data:fileCharsetTypeArray
                })
            },
            {
                xtype:'checkboxgroup',
                fieldLabel:'选项',
                id:'check_option',
                columns:1,
                items:[
                    {
                        name:'compressInsert',
                        inputValue:'Y',
                        allowBlank:true,
                        hidden:true,
                        checked:initParam['compressInsert'],
                        boxLabel:'insert语句合并'//（以5M为单位将多个insert语句进行合并）
                    },
                    {
                        name:'enableCsvTitleRow',
                        inputValue:'Y',
                        checked:initParam['enableCsvTitleRow'],
                        boxLabel:'包含属性行（选中此项CSV第1行为属性名称，否则第1行为数据）'
                    }
                ]
            },
            {
                fieldLabel:'结果集行数限制',
                editable:false,
                xtype:'combo',
                name:'tableRowsLimit',
                triggerAction:'all',
                displayField:'label',
                valueField:'data',
                queryMode:'local',
                value:initParam['tableRowsLimit'],
                forceSelection:true,
                typeAhead:true,
                store:new Ext.data.Store({
                    fields:['data' , 'label'],
                    data:rowsLimitArray
                })
            },
            {
                fieldLabel:'数据库',
                xtype:'combo',
                name:'dbName',
                blankText:'数据库选项不能为空',
                triggerAction:'all',
                displayField:'label',
                valueField:'data',
                queryMode:'local',
                forceSelection:true,
                typeAhead:true,
                value:dbName,
                store:new Ext.data.Store({
                    fields:['data','label'],
                    data:instanceDBS
                })
            },
            {
                fieldLabel:'执行SQL',
                xtype:'textarea',
                height:90,
                maxLength:20000,
                emptyText:'请在这里输入1条Select语句,SQL语句末尾一定不要加英文分号！！！',
                maxLengthText:'SQL请不要超过20000个字符',
                minLength:8,
                minLengthText:'SQL语句太短',
                name:'sql',
                value:initParam['sql'],
                allowBlank:false,
                blankText:'SQL语句不能为空'
            },
            {
            	fieldLabel:'项目组',
            	xtype:'combo',
            	triggerAction:'all',
            	displayField:'label',
            	valueField:'data',
            	queryMode:'local',
            	name:'projectName',
            	forceSelection:true,
            	typeAhead:true,
            	editable:false,
            	store:projectStore
            },
            {
                fieldLabel:'描述',
                xtype:'textarea',
                height:60,
                maxLength:1024,
                maxLengthText:'请不要超过1024个字符',
                name:'createDesc',
                value:initParam['createDesc'],
                allowBlank:true
            }
        ]
    });
    var fileTypeField = form.getForm().findField('fileType');
    var setExportCreateScript = function() {
        if(fileTypeField.getValue() == 'SQL_Insert') {
            form.getForm().findField('compressInsert').show();
            form.getForm().findField('enableCsvTitleRow').hide();
        }else {
            form.getForm().findField('compressInsert').hide();
            form.getForm().findField('enableCsvTitleRow').show();
        }
    };
    var submitTO = function() {
        if(form.isValid()) {
            var params = form.getValues();
            Ext.apply(params , advanceWindow.getAdvanceValues());

            var formParams = form.getForm().getFieldValues();
            Ext.apply(formParams , advanceWindow.getAdvanceFormValues());

            saveExportParamsToLocal(formParams , "dms_mysql_export_sql_params");

            params['exportMode'] = "sql";
            params['exportMethod'] = 'data';
            
            params['isLocal'] = isLocal;
            params['dataBaseType'] = now_db_type;
            params['dataBaseId'] = dataBase_id;
            params['dataSourceId'] = dataSource_id;
            params['dataSource'] = data_source;
            win.getEl().mask('正在提交任务，请等待....');
            ajax({
                url:getRoot()+'/dataManage/saveExportDataJob',
                params:params,
                success:function(resp) {
                    win.getEl().unmask();
                    var json = jsonDecode(resp.responseText);
                    if(json.success) {
                        public_export_grid.store.load();
                        showMonitor(json.root);
                        win.close();
                    }else {
                        $.message.error(json.root);
                    }
                },
                failure:function() {
                    win.getEl().unmask();
                }
            });
        }
    };
    fileTypeField.on('select' , setExportCreateScript);
    var win = new IDB.Window({
        title:'新增SQL导出任务',
        width:850,
        height:420,
        closable:true,
        layout:'fit',
        items:[form],
        buttons:[{
            text:'确定',handler:submitTO
        },{
            text:'关闭',handler:function() {
                win.close();
            }
        }]
    });

    nowWindow = win;
    var advanceWindow = createOnlyDataAdvanceWindow(initParam);
    win.on('beforedestroy' , function() {
        advanceWindow.close();
    });
};
var public_export_grid;
var createExportViewList = function() {
    var delAction = function() {
        var selectRows = gridPanel.getSelectionModel().getSelection();
        if(selectRows && selectRows.length > 0) {
            var selectedRow = selectRows[0];
            Ext.Msg.confirm('提示' , '真的要删除该任务吗？' , function(v) {
                if(v == 'yes') {
                    var id = selectedRow.get('id');
                    Ext.getBody().mask('正在进行处理，请等待....');
                    ajax({
                        url:getRoot()+'/dataManage/deleteJob',
                        params:{id:id},
                        success:function(resp) {
                            Ext.getBody().unmask();
                            var json = jsonDecode(resp.responseText);
                            if(json.success) {
                            	$.message.success(json.root);
                                gridPanel.store.load();
                            }else {
                                $.message.error(json.root);
                            }
                        },
                        failure:function() {
                            Ext.getBody().unmask();
                        }
                    })
                }
            });
        }else {
            $.message.warning('请先选择要删除的任务。');
        }
    };

    var gridPanel = new Ext.grid.Panel({
        selType:'rowmodel',
        title:'',//友情提示：导出任务的文件只保留7天，在任务执行后请确保尽快下载。
        region:'center',
        viewConfig: {
            enableTextSelection: true
        },
        tbar:[
            {
                text:'新增任务',iconCls:'addIcon',menu:[
                {
                    text:'导出数据库' ,
                    hidden:true,
                    handler:function() {
                        addNewDBJob();
                    }
                },
                {
                    text:'结果集导出',
                    handler:function() {
                        addNewSQLJob();
                    }
                },
                {
                    text:'快速导出库',
                    hidden:true,
                    autoScroll:true,
                    menu:instanceDBMenu
                }
            ]
            },{
                text:'删除任务',iconCls:'deleteIcon',handler:delAction
            },
            {
                text:'刷新',iconCls:'fa fa-refresh',handler:function() {
                gridPanel.store.load();
            }
            }
        ],
        columns:[
            {xtype: 'rownumberer'},
            { text: '任务号',  dataIndex: 'id' ,width:75,renderer:function(v) {
                return '<a href="javascript:Ext.getCmp(\'' + gridPanel.id + '\').showDetail()">' + v + '</a>';
            }},
            {text:'任务类型',dataIndex:'exportMode',width:85,renderer:function(v){
                return v == 'sql' ? 'SQL结果集' : "数据库表"
            }},
            { text: '状态' ,dataIndex:'exportStatus' , width:140,renderer:allStatusRenderer},
            { text: '进度' , dataIndex:'completeSize' , width:235,renderer:function(v,c,row) {
                var use = getProcess(row.data);
                var inColor = '#00DB00;';
                if(Ext.isIE) {
                    return '<div> <div style="margin-top:0;margin-left:0;background-color:#E0DCDD;width:180px;display:block;text-align:left;height:16px;float:left">'
                        +   '<div style="background-color:' + inColor + ' width:' + use + '%;float:left;height:100%"></div></div>';
                }
                return '<div> <div style="margin-top:0;margin-left:0;background-color:#E0DCDD;width:180px;display:block;text-align:left;height:16px;float:left">'
                    +   '<div style="background-color:' + inColor + ' width:' + use + '%;float:left;height:100%">&nbsp;&nbsp;</div>'
                    + '</div><span style="margin-top: 5px;">' + use + '%</span></div>';
            }},
            //{ text: '表数量' ,dataIndex:'exportTabNum' , width:70},
            { text: '已导行数' ,dataIndex:'nowRows' , width:90,renderer:function(v) {
                return commons_tools.numberWithCommas(v);
            }},
            { text: '库' ,dataIndex:'dbName' , width:130},
            { text: '执行时间' ,dataIndex:'executeTime' , width:140},
            { text: '描述' , dataIndex:'createDesc' , width:300}
        ], store:new Ext.data.Store({
            autoLoad:true,
            fields:[
                'id' , 'createDesc' , 'exportTabNum' , 'exportTabSize' ,'exportStatus' ,
                'gmtCreate' , 'gmtModified' , 'executeTime' , 'executeEndTime' , 'timeDelay',
                'dbName' , 'fileType' , 'fileCharset' , 'userName' , 'userCompany' , 'statusName',
                'instanceDesc' , 'dbUser' , 'createScript' , 'allFileName','completeSize',
                'preRows' , 'nowRows' , 'compressInsert','exportedTabs','exportMode'
            ],
            proxy: {
                url:getRoot()+'/dataManage/showExportDataList?databaseType='+ now_db_type,
                type: 'ajax',
                reader: {
                    root: 'root',
                    idProperty:'id'
                }
            }
        }),
        showDetail:function() {
            var selectRow = gridPanel.getSelectionModel().getSelection()[0];
            showDetail(selectRow.get('id'));
        }
    });
    public_export_grid = gridPanel;

    setInterval(function() {
        if(!isMonitorTask) {
            var waitingTask = false;
            gridPanel.store.each(function(record) {
                if(!waitingTask && (record.get('exportStatus') === 'NEW' || record.get('exportStatus') === 'EXPORT')) {
                    waitingTask = true;
                }
            });
            if(waitingTask) {
                gridPanel.store.load();
            }
        }
    } , 12000);
    return gridPanel;
};
var showDetail = function(id) {
    Ext.getBody().mask('正在加载...');
    ajax({
        url:'/data/export/getJobContent.do',
        params:{id:id},
        success:function(resp) {
            Ext.getBody().unmask();
            var json = jsonDecode(resp.responseText);
            if(json.success) {
                if(json.root['exportMode'] == 'sql') {
                    showMonitor(id);
                }else {
                    var window_id = 'tmp_' + tmpNum;
                    tmpNum++;
                    var win = new IDB.Window({
                        id:window_id ,width:800,height:460,title:'任务详情',layout:'border',closable:true,
                        items:[
                            createViewContent(json.root),
                            createDownloadList(json.root , window_id)
                        ]
                    });
                }
            }else {
                $.message.error(json.root);
            }
        },
        failure:function() {
            Ext.getBody().unmask();
        }
    });
};
var getJSONValue = function(json , key) {
    return json[key] || '';
};
var createDownloadList = function(data,id) {
    var title = "下载文件列表";
    if(data['allFileName']) {
        title += ' <a style="color: red" href="javascript:downloadAllFile(\'' + getJSONValue(data , 'id') + '\')" >下载总文件</a>';
    }
    var grid = new Ext.grid.Panel({
        title:title,
        region:'center',
        selType:'rowmodel',
        viewConfig: {
            enableTextSelection: true
        },
        columns:[
            {xtype: 'rownumberer'},
            { text: '表名称',  dataIndex: 'tableName' ,width:190},
            { text: '行数' ,dataIndex:'preRows' , width:70,renderer:function(v,c,row) {
                var processRows = row.get('processedRows') || 0;
                if(row.get('status') == 'END') {
                    return processRows + "/" + processRows;
                }
                return processRows + "/" + row.get('preRows')
            }},
            { text: '容量' ,dataIndex:'tableSize' , width:70,renderer:renderSize},
            { text: '开始时间' ,dataIndex:'beginTime' , width:160},
            { text: '状态' , dataIndex:'status' , width:85,renderer:allStatusRenderer},
            { text: '操作' ,dataIndex:'endTime' , width:160,renderer:function(v,c,record) {
                var status = record.get('status');
                if(status == 'END') {
                    var h =  '<a href="javascript:Ext.getCmp(\'' + grid.id + '\').showLogs()">查看日志</a> ';
                    if(data['everyTableFile'] == 'Y') {
                        h += '<a href="javascript:Ext.getCmp(\'' + grid.id + '\').downLoadFile()">下载</a>';
                    }
                    return h;
                }else if(status == 'ERROR') {
                    return '<a href="javascript:Ext.getCmp(\'' + grid.id + '\').showLogs()">查看日志</a> ';
                }else if(status == 'EXPIRED') {
                    return '<a href="javascript:Ext.getCmp(\'' + grid.id + '\').showLogs()">查看日志</a> ' + ' 文件失效';
                }
            }}
        ],
        store:new Ext.data.Store({
            autoLoad:true,
            fields:['id' , 'exportId' , 'tableName' , 'preRows' , 'realRows' ,'processedRows' ,
                'tableSize' , 'beginTime' , 'endTime' , 'timeDelay', 'fileName' , 'phyFileName' ,
                'status' , 'statusName' , 'exportMode'],
            proxy: {
                url:'/data/export/showExportListDetail.do?exportId=' + data['id'],
                type: 'ajax',
                reader: {
                    root: 'root',
                    idProperty:'id'
                }
            }
        }),
        showLogs:function() {
            var selectRow = grid.getSelectionModel().getSelection()[0];
            Ext.getCmp(id).getEl().mask('正在获取执行日志信息....');
            ajax({
                url:'/data/export/getLogContent.do',
                params:{id:selectRow.get('id')},
                success:function(resp) {
                    Ext.getCmp(id).getEl().unmask();
                    var json = jsonDecode(resp.responseText);
                    if(json.success) {
                        grid.showLogWindow(json.root);
                    }else {
                        $.message.error(json.root);
                    }
                }
            });
        },
        showLogWindow:function(content) {
            var win = new IDB.Window({
                width:600 , height:460 ,title:'执行日志',closable:true,autoScroll:true,
                html:'<pre>' + content + '</pre>'
            });
        },
        downLoadFile:function() {
            var selectRow = grid.getSelectionModel().getSelection()[0];
            downLoadFileByURL("/mysql/data/export/downLoadFile.do?id=" + selectRow.get('id') + "&token=" + getUserToken());
        }
    });
    return grid;
};
var nowContent = null;
var showContent = function(content) {
    var tmp = Ext.util.Format.htmlDecode(content);
    if(tmp && tmp.length > 100) {
        nowContent = tmp;
        return Ext.util.Format.htmlEncode(tmp.substring(0 , 100)) + '...<a href="javascript:showAllContent()">查看全部</a>';
    }
    return content;
};
var showAllContent = function() {
    var win = new IDB.Window({
        title:'备注详情',layout:'fit',width:600,height:400,closable:true,items:[{
            xtype:'textarea',value:nowContent
        }]
    })
};
var downloadAllFile = function(id) {
    downLoadFileByURL(getRoot()+"/dataManage/downLoadAllFile?id=" + id);
};
var view_tool = {
    getBaseInfoByRecord:function(record) {
        var content = '导出数据库：[' + getJSONValue(record , 'dbName') + "]中的 " +
            getJSONValue(record , 'exportTabNum') + " 个表";
        if(record['exportStatus'] == 'EXPORT') {
            content += "（已导出：" + getJSONValue(record , 'exportedTabs') +" 个表）";
        }
        return content + "，涉及表容量：" +
            commons_tools.getSizeName(parseFloat(getJSONValue(record , 'exportTabSize')) , 2) +
            "，当前执行状态：" + getJSONValue(record , 'statusName');
    },
    getExecuteInfoByRecord:function(record) {
        var content = "任务创建于：[" + getJSONValue(record , 'gmtCreate') + "]";
        if(record['executeTime']) {
            content += '，执行于：[' + record['executeTime'] + "]";
            if(record['timeDelayName']) {
                content += '，总耗时：[' + record['timeDelayName'] + "]";
            }else {
                content += '任务还在执行中。';
            }
        }else {
            content += '任务正在等待执行。';
        }
        return content;
    },
    getOptionObjectsByRecord:function(record) {
        var content = "使用账号：[" + getJSONValue(record , 'dbUser') + "]导出库：[" + getJSONValue(record , 'dbName') + "]的";
        if(record['exportMethod'] == 'all') {
            content += ' 数据和结构';
        }else if(record['exportMethod'] == 'data') {
            content += ' 数据（不含结构）';
        }else {
            content += ' 结构（CREATE TABLE语句）';
        }
        content += "，其它对象：[";
        var hasOtherObject = false;
        if(record['exportProcedure'] == 'Y') {
            content += "存储过程，";hasOtherObject = true;
        }
        if(record['exportFunction'] == 'Y') {
            content += "函数，";hasOtherObject = true;
        }
        if(record['exportTrigger'] == 'Y') {
            content += "触发器，";hasOtherObject = true;
        }
        if(record['exportEvent'] == 'Y') {
            content += "事件，";hasOtherObject = true;
        }
        if(record['exportView'] == 'Y') {
            content += "视图，";hasOtherObject = true;
        }
        if(hasOtherObject) {
            content = content.substring(0 , content.length - 1) + "]";
        }else {
            content += " 无 ]"
        }
        return content;
    },
    getDescByRecord:function(record) {
        var content = "[ ";
        if(record['fileType'] == 'SQL_Insert') {
            content += "SQL文件，";
        }else {
            content += "CSV文件，";
        }
        content += record['fileCharset'] + " ] ";
        return content + getJSONValue(record , 'createDesc');
    }
};
var createViewContent = function(record) {
    var items = [{
        html:'<span style="font-size: 13px;"><span style="font-weight: bold">基本信息：</span>' + view_tool.getBaseInfoByRecord(record) + "</span>"
    },{
        html:'<span style="font-size: 13px;"><span style="font-weight: bold">执行情况：</span>' + view_tool.getExecuteInfoByRecord(record) + "</span>"
    },{
        html:'<span style="font-size: 13px;"><span style="font-weight: bold">执行情况：</span>' + view_tool.getOptionObjectsByRecord(record) + "</span>"
    },{
        html:'<span style="font-size: 13px;"><span style="font-weight: bold">备注：</span>' + view_tool.getDescByRecord(record) + "</span>"
    }];
    return new Ext.Panel({
        region:'north',height:150,
        border:false,
        defaults:{
            xtype:'panel',
            border:false,
            margin: '13 2 0 10',
            width:'100%',
            flex: 1
        },
        layout:{
            type: 'vbox'
        },
        items:items
    });
};